package com.wft.design.oauth.service.impl;

import com.wft.design.common.security.bean.Authentication;
import com.wft.design.oauth.entity.OauthClient;
import com.wft.design.oauth.entity.OauthParameter;
import com.wft.design.oauth.service.OauthClientService;
import com.wft.design.oauth.service.RefreshTokenService;
import com.wft.design.oauth.service.GrantModeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;

/**
 * @author WFT
 * @date 2019/12/22
 * description: 刷新Token策略
 */
@Service
@RequiredArgsConstructor
public class RefreshTokenModeServiceImpl implements GrantModeService {

    private final static String GRANT_TYPE = "refresh_token";

    private final RefreshTokenService refreshTokenService;
    private final OauthClientService clientService;

    @Override
    public String getName() {
        return GRANT_TYPE;
    }

    @Override
    public Authentication checking(OauthParameter parameter) {
        //  令牌校验
        Assert.hasText(parameter.getRefreshToken(),"刷新令牌不能为空");
        //  获取认证信息
        Authentication authentication = this.refreshTokenService.getAuthentication(parameter.getRefreshToken());
        //  校验clientId和密钥
        OauthClient client = this.clientService.selectById(parameter.getClientId());
        Assert.notNull(client,"客户端Id不存在");
        String cipherText = DigestUtils.md5DigestAsHex((client.getSecret() + parameter.getRefreshToken()).getBytes());
        Assert.isTrue(cipherText.equals(parameter.getClientSecret()),"客户端密钥不正确");
        return authentication;
    }
}
